﻿/*
easyUI动态树控件(以下说明是treegrid属性方法之外的)
options={
EndColumns: [{ field: 'remarks', title: '备注', width: 100 }],
DynamicColumns:
[
{
    field: 'Price', title: '性别', width: '100'
}
],
CallRelation: {
                    H: [{ TargetField: "total", SubField: ["amount"] }],
                    V: [
                        { TargetField: "total", MarkFiled: "subject", TargetMark: "总用地面积", SubMark: ["住宅", "商业"] },
                        { TargetField: "amount", MarkFiled: "id", TargetMark: "1", SubMark: [7, 11] }
                    ]
                }
data:
{
"DynamicRows": [
        {
            "Group": "",
            "Name": "test1",
            "Data": [
                { "price": 75, "count": 200 },
                { "price": 45, "count": 120 },
                { "price": 15, "count": 180 },
                { "price": 15, "count": 180 },
                { "price": 15, "count": 180 },
                { "price": 15, "count": 180 },
                { "price": 15, "count": 180 }
            ]
        },
        {
            "Name": "test2",
            "Data": [
                { "price": 100, "count": 200 },
                { "price": 10, "count": 120 },
                { "price": 25, "count": 170 },
                { "price": 25, "count": 170 },
                { "price": 25, "count": 170 },
                { "price": 25, "count": 170 },
                { "price": 25, "count": 170 }
            ]
        }
    ],
    "DynamicFooter": [
        [{"price" : 110, "count" : 1040}],
        [{ "price": 120, "count": 200 }]
    ]
}
}
*/

(function ($) {
    var _CurrentEdit;
    var _IsFirstEdit = true;
    var _ChangedField = [];
    var _Field2Column = {};
    var _Editor = {
        "numberbox": '<DIV class="datagrid-cell datagrid-cell-c2-count_0 datagrid-editable" style="HEIGHT: auto; WIDTH: 79px" jQuery111108605553062018629="266"><TABLE border=0 cellSpacing=0 cellPadding=1 jQuery111108605553062018629="262"><TBODY><TR><TD><INPUT class="datagrid-editable-input numberbox-f textbox-f" style="DISPLAY: none" type=text value=#value# jQuery111108605553062018629="264"><SPAN class="textbox numberbox" style="HEIGHT: 20px; WIDTH: 77px"><INPUT class="textbox-text validatebox-text" style="WIDTH: 69px; IME-MODE: disabled; PADDING-BOTTOM: 3px; PADDING-TOP: 3px; MARGIN-LEFT: 0px; MARGIN-RIGHT: 0px" value=#value# autocomplete="off" jQuery111108605553062018629="265"><INPUT class=textbox-value type=hidden value=#value#></SPAN></TD></TR></TBODY></TABLE></DIV>',
        "textbox": '<DIV class="datagrid-cell datagrid-cell-c2-Remark datagrid-editable" style="HEIGHT: auto; WIDTH: 99px" jQuery111106161991053280018="365"><TABLE border=0 cellSpacing=0 cellPadding=1 jQuery111106161991053280018="366"><TBODY><TR><TD><INPUT class="datagrid-editable-input textbox-f" style="DISPLAY: none" type=text value=#value# jQuery111106161991053280018="373"><SPAN class=textbox style="HEIGHT: 20px; WIDTH: 97px" jQuery111106161991053280018="371"><INPUT class="textbox-text validatebox-text" style="WIDTH: 89px; PADDING-BOTTOM: 3px; PADDING-TOP: 3px; MARGIN-LEFT: 0px; MARGIN-RIGHT: 0px" type=text value=#value# autocomplete="off" placeholder jQuery111106161991053280018="363"><INPUT class=textbox-value type=hidden value=#value#></SPAN></TD></TR></TBODY></TABLE></DIV>'
    }
    function CloneObj(obj) {
        var result = {};
        if (obj && obj.length) {
            result = [];
        }
        for (var key in obj) {
            var tmp = typeof obj[key] === 'object' ? CloneObj(obj[key]) : obj[key];
            if (obj.length) {
                result.push(tmp)
            }
            else {
                result[key] = tmp;
            }
        }
        return result;

    };

    function BeginEdit() {
        _IsFirstEdit = false;
    }
    function RowClick(row) {
        if (_CurrentEdit == row) {
            return;
        }
        var tree = $(this).parents('div .datagrid-view').children('table');
        var options = $(tree).treegrid('options');
        if (options.editing && $(tree).treegrid('isLeaf', row[options.idField])) {
            if (_CurrentEdit) {
                $(tree).treegrid('endEdit', _CurrentEdit[options.idField]);
                if ($(tree).treegrid('getEditors', _CurrentEdit[options.idField]).length > 0) {
                    return
                }
            }
            _CurrentEdit = row
            _IsFirstEdit = true;
            $(tree).treegrid('beginEdit', _CurrentEdit[options.idField]);
        }
    }
    function BaseNumberValueChange_parent(tree, options, obj, node, field, diff) {
        var sum;
        if (node == null) {
            return;
        }
        if (node[field] == "") {
            sum = 0;
        }
        else {
            sum = parseFloat(node[field].toString().replace(/,/g, ""))
        }
        var rowtmp = {};
        sum = sum.add(diff).toCurrency();
        rowtmp[field] = sum;
        node[field] = sum;
        Update(tree, options, node[options.idField], rowtmp, node);
        CallHSumRelation(tree, obj, node, field, diff, { IsCallDetail: false, IsFirst: false });
        var p = $(tree).treegrid('getParent', node[options.idField]);
        if (p) {
            BaseNumberValueChange_parent(tree, options, obj, p, field, diff)
        }
    }
    function BaseNumberValueChange(nval, oval, func) {
        if (_IsFirstEdit || nval == undefined) {
            return;
        }
        var tree = $(this).parents('div .datagrid-view').children('table');
        var obj = this
        $(tree).treegrid('loading');
        setTimeout(function () {
            _ChangedField = [];
            var field = $(obj).parents('td[field]').attr('field');
            _ChangedField.push(field);
            SetChanged(_CurrentEdit, field)
            var options = $(tree).treegrid('options');
            var p = $(tree).treegrid('getParent', _CurrentEdit[options.idField]);
            nval = nval.replace(/,/g, "")
            oval = oval.replace(/,/g, "")
            if (nval == "") {
                $(obj).numberbox('setValue', 0.00)
                nval = "0";
            }
            if (oval == "") {
                oval = "0";
            }
            if (oval != nval) {
                nval = parseFloat(nval);
                oval = parseFloat(oval);
                _CurrentEdit[field] = nval;
                var diff = parseFloat(nval.sub(oval))

                if (options.MyOption && options.MyOption.CallParentNode) {
                    BaseNumberValueChange_parent(tree, options, obj, p, field, diff);
                }
                CallHSumRelation(tree, obj, _CurrentEdit, field, diff, { IsCallDetail: false, IsFirst: true });
                var V = options.MyOption.CallRelation.V
                if (V) {
                    for (var i = 0; i < V.length; i++) {
                        CallVSumRelation(tree, field, diff, V[i]);
                    }
                }
                
                if (options.data.footer) {
                    BaseNumberValueChange_footer(tree, field, diff)
                }
            }
            $(tree).treegrid('loaded');
        }, 100)


    }
    function CallVSumRelation(tree, field, diff, V) {
        var options = $(tree).treegrid('options');
        if (V) {
            var callV = []
            for (var i = 0; i < _ChangedField.length; i++) {
                var cfield = _ChangedField[i];
                for (var j = 0; j < V.length; j++) {
                    var sumdef = V[j];
                    if (cfield == sumdef.TargetField || cfield.indexOf(sumdef.TargetField + "_") == 0) {
                        var o = CloneObj(sumdef)
                        o.TargetField = cfield;
                        callV.push(o);
                    }
                }
            }
            if (callV.length > 0) {
                var data = $(tree).treegrid('getData')
                for (var i = 0; i < callV.length; i++) {
                    var call = callV[i];
                    CallVSumRelation_sub(options, call, data)
                    if (call[options.idField]) {
                        call.Params = call.Params.replace(/\[[^\]]*\]/g, "0.00")
                        var pjson = $.parseJSON(call.Params);
                        if (call.HCall && call.HCall(_Field2Column[call.TargetField])) {
                            CallHSumRelation(tree, null, call.row, field, 0, { IsCallDetail: true, IsFirst: false })
                            if (call.onChange) {
                                call.onChange.apply(this, [{
                                    param: pjson, options: options, row: call.row, field: call.TargetField, Field2Column: _Field2Column
                                }])
                            }
                        }
                        if (call.Exclude) {
                            if (call.Exclude(_Field2Column[call.TargetField])) {
                                continue
                            }
                        }
                        var result = call.CallFunc.apply(this, [{
                            param: pjson, options: options, row: call.row, field: call.TargetField, Field2Column: _Field2Column
                        }]);
                        //if (result != call.row[call.TargetField]) {
                        var rowtmp = {};
                        rowtmp[call.TargetField] = result;
                        call.row[call.TargetField] = result
                        Update(tree, options, call[options.idField], rowtmp, call.row);
                        if (call.onChange) {
                            call.onChange.apply(this, [{
                                param: pjson, options: options, row: call.row, field: call.TargetField, Field2Column: _Field2Column
                            }])
                        }
                        //}
                    }
                }
            }
        }
    }
    function CallVSumRelation_sub(options, call, data) {
        for (var j = 0; j < data.length; j++) {
            var d = data[j];
            if (call["TargetMark"] == d[call.MarkFiled]) {
                call[options.idField] = d[options.idField];
                call.row = d;
            }
            else {
                if (d[call.TargetField]) {
                    eval("var expstr = /(\\[" + d[call.MarkFiled].replace(/\\/g, "\\").replace(/\//g, "\\/").replace(/\)/g, "\\)").replace(/\(/g, "\\(") + "\\])/g;")
                    call.Params = call.Params.replace(expstr, d[call.TargetField].toString().replace(/,/g, ""))
                }
            }
            if (d.children) {
                CallVSumRelation_sub(options, call, d.children);
            }
        }
    }
    function TransformVParam(data, field, params) {
        for (var j = 0; j < data.length; j++) {
            var d = data[j];
            if (d[field]) {
                eval("var expstr = /(\\[" + d[field].toString().replace(/\\/g, "\\").replace(/\//g, "\\/").replace(/\)/g, "\\)").replace(/\(/g, "\\(") + "\\])/g;")
                params = params.replace(expstr, d[field].toString().replace(/,/g, ""))
            }
            if (d.children) {
                params = TransformVParam(d.children, field, params);
            }
        }
        return params;
    }
    function CallHSumRelation(tree, obj, row, field, diff, op) {
        var options = $(tree).treegrid('options');
        var data = $(tree).treegrid('getData');
        if (options.MyOption && options.MyOption.CallRelation) {
            var H = options.MyOption.CallRelation.H;
            if (H) {
                for (var i = 0; i < H.length; i++) {
                    var sumdef = H[i];
                    var flag = false;

                    for (var j = 0; j < sumdef.SubField.length; j++) {
                        if (sumdef.SubField[j] == field || field.indexOf(sumdef.SubField[j] + "_") == 0) {
                            flag = true;
                            break;
                        }
                    }

                    if (flag && sumdef.ExcludeCellFunc) {
                        if (sumdef.ExcludeCellFunc(row, _Field2Column[field])) {

                        }
                    }

                    if (!flag) {
                        continue;
                    }
                    if (sumdef.Exclude) {
                        if (sumdef.Exclude(row)) {
                            _ChangedField.push(sumdef.TargetField);
                            continue
                        }
                    }
                    if (sumdef.Params) {
                        sumdef.Params = TransformVParam(data, sumdef.TargetField, sumdef.Params)
                    }
                    var sum = 0.00;


                    if (op.IsCallDetail || sumdef.IsCallDetail) {
                        for (var f in row) {
                            for (var j = 0; j < sumdef.SubField.length; j++) {
                                if (sumdef.SubField[j] == f || f.indexOf(sumdef.SubField[j] + "_") == 0) {
                                    sum = sum.add(parseFloat(row[f].toString().replace(/,/g, "")))
                                }
                            }
                        }
                    }
                    else {
                        if (row[sumdef.TargetField] != "") {
                            sum = parseFloat(row[sumdef.TargetField].toString().replace(/,/g, ""));
                        }
                        sum = sum.add(diff);
                    }
                    if (sumdef.formatter) {
                        sum = sumdef.formatter(sum)
                    }
                    var rowtmp = {};
                    var val = sum.toCurrency();
                    rowtmp[sumdef.TargetField] = val;
                    row[sumdef.TargetField] = val;
                    if (_CurrentEdit != row) {
                        Update(tree, options, row[options.idField], rowtmp, row)
                    }
                    else {
                        var editor = $(tree).treegrid('getEditor', { index: row[options.idField], field: sumdef.TargetField });
                        if (editor) {
                            $(editor.target).numberbox('setValue', row[sumdef.TargetField])
                            SetChanged(_CurrentEdit, rowtmp)
                        }
                        else {
                            Update(tree, options, row[options.idField], rowtmp, row)
                        }
                    }
                    if ($.inArray(sumdef.TargetField, _ChangedField) == -1) {
                        _ChangedField.push(sumdef.TargetField);
                    }
                    if (sumdef.ChangedField && op.IsFirst) {
                        sumdef.ChangedField(_ChangedField, field)
                    }
                    if (!row.children) {
                        BaseNumberValueChange_footer(tree, sumdef.TargetField, diff)
                    }
                    if (sumdef.onChange) {
                        sumdef.onChange(sumdef.Params, row, field, _Field2Column[sumdef.TargetField]);
                    }
                }
            }
        }
    }
    var _Footer;
    function BaseNumberValueChange_footer(tree, field, diff) {
        if (!_Footer) {
            _Footer = $(tree).treegrid('getFooterRows');
        }
        if (_Footer) {
            for (var i = 0; i < _Footer.length; i++) {
                var old = _Footer[i][field].toString().replace(/,/g, "")
                if (old == "") {
                    old = "0.00"
                }
                var val = parseFloat(old).add(diff).toCurrency()
                _Footer[i][field] = val;
                $(tree).parent("div[class*=datagrid]").find("div[class*=datagrid-footer]").find("td[field='" + field + "']").children("div").html(val)
            }
        }
    }

    function SetBaseEvent(options) {
        for (var i = 0; i < options.columns.length; i++) {
            var cols = options.columns[i];
            for (var j = 0; j < cols.length; j++) {
                var col = cols[j];
                if (!col.editor) {
                    continue;
                }
                if (!col.editor.options) {
                    col.editor.options = {};
                }
                var op = col.editor.options;
                if (col.editor.type && col.editor.type == "numberbox") {
                    if (op.onChange) {
                        var funcchange = op.onChange;
                        op.onChange = function () {
                            if (!_IsFirstEdit) {
                                var x = BaseNumberValueChange;
                                x.apply(this, arguments);
                                funcchange.apply(this, arguments);
                            }
                        }
                    }
                    else {
                        op.onChange = BaseNumberValueChange;
                    }
                }
                else {
                    var funcchange = op.onChange;
                    op.onChange = function (nval, oval) {
                        if (!_IsFirstEdit) {
                            var field = $(this).parents('td[field]').attr('field');
                            _CurrentEdit[field] = nval
                            SetChanged(_CurrentEdit, field)
                            if (funcchange) {
                                funcchange.apply(this, arguments);
                            }
                        }
                    }
                }
            }
        }
        if (options.onClickRow) {
            var funcclick = options.onClickRow;
            options.onClickRow = function (row) {
                var x = RowClick;
                x.apply(this, arguments);
                funcclick.apply(this, arguments);
            }
        }
        else {
            options.onClickRow = RowClick;
        }
        if (options.onBeginEdit) {
            var funcedit = options.onBeginEdit;
            options.onBeginEdit = function () {
                var x = BeginEdit;
                x.apply(this, arguments);
                funcedit.apply(this, arguments);
            }
        }
        else {
            options.onBeginEdit = BeginEdit;
        }

    }
    function DataTransform(options) {
        var Rand = Math.random();
        $.ajax({
            type: options.method, url: options.url + "?rand=" + Rand, data: $.extend({}, options.queryParams), dataType: "json", async: false, success: function (data) {
                options.url = "";
                options.data = data;
            }, error: function (ex) {
            }
        });
        var data = options.data;
        if (!data) {
            //无数据
            return;
        }
        var DynamicData = data.DynamicRows;
        if (DynamicData) {
            var clen = options.columns.length - 1
            var Groupflag = false;
            var arrGroup = [];
            var lastgroup = "";
            var groupstart = "";
            var maxrowspan = 1;
            for (var i = 0; i < DynamicData.length; i++) {
                var sub = DynamicData[i];
                if (sub.Group) {
                    if (sub.Group != lastgroup) {
                        groupstart = i;
                        lastgroup = sub.Group;
                        var count = 1;
                        if (i + 1 < DynamicData.length) {
                            for (var j = i + 1; j < DynamicData.length; j++) {
                                if (DynamicData[j].Group == sub.Group) {
                                    count++;
                                }
                            }
                        }
                        var sumwidth = 0;
                        for (var j = 0; j < options.MyOption.DynamicColumns.length; j++) {
                            sumwidth = sumwidth.add(parseFloat(options.MyOption.DynamicColumns[j].width));
                        }

                        var g = {
                            title: sub.Group,
                            width: sumwidth * count,
                            colspan: count * options.MyOption.DynamicColumns.length
                        };
                        if (options.colGroupField && sub[options.colGroupField] != undefined) {
                            //分组ID
                            g.colgroup = sub[options.colGroupField];
                        }
                        arrGroup.push(g)
                        Groupflag = true;
                    }
                    else {
                        if (options.MyOption.CallRelation && options.MyOption.CallRelation.DynamicGroupH) {
                            for (var j = 0; j < options.MyOption.CallRelation.DynamicGroupH.length; j++) {
                                var dh = CloneObj(options.MyOption.CallRelation.DynamicGroupH[j]);
                                if (sub.Name == dh.Name) {
                                    if (!options.MyOption.CallRelation.H) {
                                        options.MyOption.CallRelation.H = [];
                                    }
                                    var Target = dh.TargetField;
                                    dh.TargetField = Target + "_" + i.toString();
                                    dh.SubField = []
                                    for (var x = groupstart; x < i; x++) {
                                        dh.SubField.push(Target + "_" + x.toString())
                                    }
                                    options.MyOption.CallRelation.H.push(dh)
                                }
                            }
                        }
                    }
                }
            }
            if (Groupflag) {
                maxrowspan++;
            }
            var dyncols = options.columns[clen];
            for (var i = 0; i < DynamicData.length; i++) {
                var sub = DynamicData[i];
                if (sub.Data.length == 0 && sub.Name == "") {
                    continue;
                }

                var isgroup = (sub.Name != null && sub.Name && options.MyOption.DynamicColumns.length > 1)
                if (isgroup) {
                    if (i == 0) {
                        for (var x = 0; x < options.columns[clen].length; x++) {
                            if (options.columns[clen][x].rowspan) {
                                options.columns[clen][x].rowspan = options.columns[clen][x].rowspan + 1;
                            }
                            else {
                                options.columns[clen][x].rowspan = 2;
                            }
                            if (Groupflag) {
                                options.columns[clen][x].rowspan = options.columns[clen][x].rowspan + 1;
                            }
                        }
                        if (Groupflag) {
                            for (var x = 0; x < arrGroup.length; x++) {
                                options.columns[clen].push(arrGroup[x]);
                            }
                            Groupflag = false;
                        }
                        clen++;
                        maxrowspan++;
                        options.columns[clen] = [];
                        clen++;
                        options.columns[clen] = [];
                        dyncols = options.columns[clen]
                    }
                    var dynlen = options.MyOption.DynamicColumns.length;
                    var objfield = { title: sub.Name, colspan: dynlen }
                    options.columns[clen - 1].push(objfield);
                }
                if (Groupflag) {
                    for (var x = 0; x < options.columns[clen].length; x++) {
                        if (options.columns[clen][x].rowspan) {
                            options.columns[clen][x].rowspan = options.columns[clen][x].rowspan + 1;
                        }
                        else {
                            options.columns[clen][x].rowspan = 2;
                        }
                    }
                    for (var x = 0; x < arrGroup.length; x++) {
                        options.columns[clen].push(arrGroup[x]);
                    }
                    clen++;
                    options.columns[clen] = [];
                    dyncols = options.columns[clen]
                    Groupflag = false;
                }
                for (var j = 0; j < options.MyOption.DynamicColumns.length; j++) {
                    var col = options.MyOption.DynamicColumns[j];
                    if (options.MyOption.DynamicColumnOptions && options.MyOption.DynamicColumnOptions[sub.Name]) {
                        col = options.MyOption.DynamicColumnOptions[sub.Name]
                    }
                    var field = col.field + "_" + i.toString();
                    var coltmp = CloneObj(col)
                    coltmp.field = field;
                    if (options.colGroupField && sub[options.colGroupField] != undefined) {
                        //分组ID
                        coltmp.colgroup = sub[options.colGroupField];
                    }
                    if (!isgroup) {
                        coltmp.title = sub.Name;
                    }
                    _Field2Column[field] = coltmp;
                    coltmp.DynamicData = sub;
                    dyncols.push(coltmp)
                    for (var y = 0; y < sub.Data.length; y++) {
                        var subitem = sub.Data[y];
                        data.rows[y][field] = subitem[col.field];
                    }
                }
            }
            if (options.MyOption && options.MyOption.EndColumns) {
                for (var i = 0; i < options.MyOption.EndColumns.length; i++) {
                    options.MyOption.EndColumns[i].rowspan = maxrowspan;
                    options.columns[0].push(options.MyOption.EndColumns[i])
                }
            }
            var footer = data.footer;
            if (footer) {
                for (var i = 0; i < footer.length; i++) {
                    for (var j = 0; j < options.MyOption.DynamicColumns.length; j++) {
                        var col = options.MyOption.DynamicColumns[j];
                        for (var y = 0; y < data.DynamicFooter.length; y++) {
                            var field = col.field + "_" + y.toString();
                            var footeritem = data.DynamicFooter[y][i];
                            if (footeritem) {
                                footer[i][field] = footeritem[col.field];
                            }

                        }
                    }
                }
            }
            if (options.MyOption && options.MyOption.CallRelation && options.MyOption.DynamicColumns) {
                var VArr = options.MyOption.CallRelation.V;
                if (VArr) {
                    for (var vindex = 0; vindex < VArr.length; vindex++) {
                        var V = VArr[vindex];
                        var vtmp = CloneObj(V)
                        var index = 0;
                        for (var i = 0; i < vtmp.length; i++) {
                            var flag = false;
                            for (var j = 0; j < options.MyOption.DynamicColumns.length; j++) {
                                if (vtmp[i].TargetField == options.MyOption.DynamicColumns[j].field) {
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag) {
                                for (var x = 0; x < DynamicData.length; x++) {
                                    var vdef = CloneObj(vtmp[i]);
                                    vdef.TargetField = vdef.TargetField + "_" + x.toString()
                                    if (x == 0) {
                                        V.splice(index, 1, vdef);
                                    }
                                    else {
                                        V.splice(index, 0, vdef);
                                    }
                                    index++;
                                }
                            }
                            else {
                                index++;
                            }
                        }
                    }
                    
                }
            }
        }


        SetBaseEvent(options);
    }
    function Update(tree, options, index, obj, row) {
        var tr = $("tr[node-id='" + index + "']");
        for (var v in obj) {
            tr.children("td[field=" + v + "]").children("div").html(obj[v])
        }
        if (row) {
            SetChanged(row, obj)
        }
        else {
            var filter = {
                RowFilter: { MarkFiled: "", TargetMark: "" }
            }
            filter.RowFilter.MarkFiled = options.idField
            filter.RowFilter.TargetMark = index
            var row = GetRow(tree, filter)
            for (var v in obj) {
                row[v] = obj[v]
            }
            SetChanged(row, obj)
        }
    }
    function SetChanged(row, obj) {
        if (!row.ChangedFields) {
            row.ChangedFields = []
        }
        if (typeof (obj) == "string") {
            if ($.inArray(obj, row.ChangedFields) == -1) {
                row.ChangedFields.push(obj)
            }
        }
        else {
            for (var v in obj) {
                if ($.inArray(v, row.ChangedFields) == -1) {
                    row.ChangedFields.push(v)
                }
            }
        }

    }
    function GetCellValue_sub(data, param) {
        for (var i = 0; i < data.length; i++) {
            var row = data[i];
            if (row[param.RowFilter.MarkFiled] == param.RowFilter.TargetMark) {
                for (var f in row) {
                    var col = _Field2Column[f]
                    if (col) {
                        if (param.ColumnFilter.Group && col.DynamicData.Group != param.ColumnFilter.Group) {
                            continue
                        }
                        if ((param.ColumnFilter.MatchFunc && param.ColumnFilter.MatchFunc(col)) || col.title == param.ColumnFilter.Name || f == param.ColumnFilter.Filed) {
                            return parseFloat(row[f].toString().replace(/,/g, ""))
                        }
                    }
                }
            }
            if (row.children) {
                var val = GetCellValue_sub(row.children, param)
                if (val != undefined) {
                    return val;
                }
            }
        }

    }
    function GetCellValue(tree, param) {
        var data = $(tree).treegrid('getData');
        return GetCellValue_sub(data, param)

    }

    function GetRow_sub(data, param) {
        for (var i = 0; i < data.length; i++) {
            var row = data[i];
            if (row[param.RowFilter.MarkFiled] == param.RowFilter.TargetMark) {
                return row
            }
            if (row.children) {
                var val = GetRow_sub(row.children, param)
                if (val) {
                    return val;
                }
            }
        }

    }
    function GetRow(tree, param) {
        var data = $(tree).treegrid('getData');
        return GetRow_sub(data, param)

    }
    function GetGroupColumn(tree, group) {
        var options = $(tree).treegrid('options');
        var re = [];
        for (var i = 0; i < options.columns.length; i++) {
            for (var j = 0; j < options.columns[i].length; j++) {
                var col = options.columns[i][j];
                if (col.DynamicData) {
                    if (!group || col.DynamicData.Group == group) {
                        re.push(col);
                    }
                }
            }
        }
        return re

    }
    function GetDynamicData(tree) {
        var data = $(tree).treegrid('getData');
        var changes = [];
        var options = $(tree).treegrid('options');
        for (var i = 0; i < data.length; i++) {
            GetDynamicData_sub(data[i], options, changes);
        }
        var updatedata = $(tree).treegrid('getChanges', 'updated');
        for (var i = 0; i < updatedata.length; i++) {
            var flag = true;
            for (var j = 0; j < changes.length; j++) {
                if (changes[j].BaseData[options.idField] == updatedata[i][options.idField]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                changes.push(GetDynamicData_createobj(updatedata[i], options, changes));
            }
        }
        return changes;
    }
    function GetDynamicData_sub(row, options, changes) {
        if (row.ChangedFields && row.ChangedFields.length > 0) {
            changes.push(GetDynamicData_createobj(row, options));
        }
        if (row.children) {
            for (var i = 0; i < row.children.length; i++) {
                GetDynamicData_sub(row.children[i], options, changes);
            }
        }
    }
    function ClearChangeFlag(rows) {
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i]
            if (row.ChangedFields) {
                row.ChangedFields = []
            }
            if (rows[i].children) {
                ClearChangeFlag(rows[i].children);
            }
        }
    }
    function GetDynamicData_createobj(row, options) {
        var data = { BaseData: {}, DynamicData: [] };
        var baseobj = CloneObj(row);
        delete baseobj["children"];
        for (var i = 0; i < options.data.DynamicRows.length; i++) {
            var dynamicobj = null;
            for (var j = 0; j < options.MyOption.DynamicColumns.length; j++) {
                var filed = options.MyOption.DynamicColumns[j].field;
                var filedEx = filed + "_" + i.toString();
                if ($.inArray(filedEx, row.ChangedFields) != -1) {
                    if (dynamicobj == null) {
                        dynamicobj = CloneObj(options.data.DynamicRows[i]);
                    }
                    dynamicobj[filed] = baseobj[filedEx];
                }
                delete baseobj[filedEx];
            }
            if (dynamicobj != null) {
                delete dynamicobj["Data"];
                data.DynamicData.push(dynamicobj);
            }

        }
        delete baseobj["ChangedFields"];
        data.BaseData = baseobj;
        return data;
    }
    $.fn.DynamicTree = function (options, param) {
        if (typeof options == "string") {
            var func = $.fn.DynamicTree.methods[options];
            if (func) {
                return func(this, param);
            } else {
                func = $.fn.treegrid.methods[options];
                if (func) {
                    return func(this, param);
                }
                else {
                    return this.treegrid(options, param);
                }
            }
        }
        options.editing = false;
        var tree = this;
        var url = options.url;
        options.url = "";
        options.data = null;
        var re = tree.treegrid(options, param)
        options.url = url
        tree.treegrid('loading');
        setTimeout(function () {
            if (_CurrentEdit) {
                try {
                    tree.treegrid("cancelEdit", _CurrentEdit[options.idField]);
                }
                catch (ex) { }
            }
            _Field2Column = {};
            DataTransform(options);
            re = tree.treegrid(options, param)
            tree.treegrid('rejectChanges');
        }, 100)
        return re;
    };
    $.fn.DynamicTree.methods = {
        edit: function (tree, flag) {
            var options = $(tree).treegrid('options');
            options.editing = flag;
            if (!flag && _CurrentEdit) {
                $(tree).treegrid('endEdit', _CurrentEdit[options.idField]);
                if ($(tree).treegrid('getEditors', _CurrentEdit[options.idField]).length > 0) {
                    return false;
                }

                var data = $(tree).treegrid('getData');
                ClearChangeFlag(data);
                $(tree).treegrid('acceptChanges')
                _CurrentEdit = null;
            }
            return true;
        },
        GetEditRow: function (tree) {
            return _CurrentEdit;
        },
        GetDynamicData: function (tree) {
            return GetDynamicData(tree);
        },
        update: function (tree, obj) {
            var options = $(tree).treegrid('options');
            return Update(tree, options, obj[options.idField], obj.row, null)
        },
        GetCellValue: function (tree, obj) {
            return GetCellValue(tree, obj)
        },
        GetRow: function (tree, obj) {
            return GetRow(tree, obj)
        },
        GetGroupColumn: function (tree, obj) {
            return GetGroupColumn(tree, obj)
        }
    }
    $.fn.DynamicTree.prototype = $.fn.treegrid;
})(jQuery);
